#include "fwESContext.h"

ESContext::ESContext()
	: _eglHWND(NULL), _eglContext(NULL), _eglDisplay(NULL), _eglSurface(NULL)
{
	LOGIDBG("Init ESContext\n");
}

ESContext::~ESContext()
{
	LOGIDBG("Destroy ESContext\n");
	//SAFE_DEL(_eglHWND);
	//SAFE_DEL(_eglContext);
	//SAFE_DEL(_eglDisplay);
	//SAFE_DEL(_eglSurface);
}

EGLBoolean ESContext::CreateESContext(EGLint attrs[])
{
	EGLint numConfigs;
	EGLint majorVersion;
	EGLint minorVersion;
	EGLDisplay display;
	EGLContext context;
	EGLSurface surface;
	EGLConfig config;
	EGLint contextAttribs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE, EGL_NONE };

	display = eglGetDisplay(GetDC(_eglHWND));
	if (display == EGL_NO_DISPLAY)
	{
		return EGL_FALSE;
	}

	if (!eglInitialize(display, &majorVersion, &minorVersion))
	{
		return EGL_FALSE;
	}

	if (!eglGetConfigs(display, NULL, 0, &numConfigs))
	{
		return EGL_FALSE;
	}

	if (!eglChooseConfig(display, attrs, &config, 1, &numConfigs))
	{
		return EGL_FALSE;
	}

	surface = eglCreateWindowSurface(display, config, (EGLNativeWindowType)_eglHWND, NULL);
	if (surface == EGL_NO_SURFACE)
	{
		return EGL_FALSE;
	}

	context = eglCreateContext(display, config, EGL_NO_CONTEXT, contextAttribs);
	if (context == EGL_NO_CONTEXT)
	{
		return EGL_FALSE;
	}

	if (!eglMakeCurrent(display, surface, surface, context))
	{
		return EGL_FALSE;
	}

	_eglDisplay = display;
	_eglSurface = surface;
	_eglContext = context;

	return EGL_TRUE;
}